using System;

using JetBrains.Annotations;

namespace Rsdn.SmartApp
{
	/// <summary>
	/// Helper methods for <see cref="IObservable{T}"/>/<see cref="IObserver{T}"/>.
	/// </summary>
	public static class ObservableHelper
	{
		/// <summary>
		/// Subscribe to observable with delegate for OnNext.
		/// </summary>
		public static IDisposable Subscribe<T>(
			[NotNull] this IObservable<T> observable,
			[NotNull] Action<T> nextAction)
		{
			if (observable == null)
				throw new ArgumentNullException("observable");
			if (nextAction == null)
				throw new ArgumentNullException("nextAction");

			return observable.Subscribe(CreateObserver(nextAction));
		}

		/// <summary>
		/// Create observable with delegate for OnNext.
		/// </summary>
		public static IObserver<T> CreateObserver<T>(
			[NotNull] Action<T> nextAction)
		{
			if (nextAction == null)
				throw new ArgumentNullException("nextAction");

			return new Observer<T>(nextAction);
		}

		#region Observer class
		private class Observer<T> : IObserver<T>
		{
			private readonly Action<T> _nextAction;

			public Observer(Action<T> nextAction)
			{
				_nextAction = nextAction;
			}

			#region Implementation of IObserver<T>
			public void OnNext(T item)
			{
				_nextAction(item);
			}

			public void OnCompleted()
			{
			}

			public void OnError(Exception exception)
			{
			}
			#endregion
		}
		#endregion
	}
}